<template>
	<view class="container">
		<canvas :canvas-id="canvasId" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>
	</view>
</template>

<script>
	export default {
		name: "ProgressBar",
		props: {
			duration: {
				type: Number,
				default: 5000, // 默认倒计时5秒
			},
			progressBarColor: {
				type: String,
				default: '#76c7c0', // 默认进度条颜色
			},
			backgroundColor: {
				type: String,
				default: '#e0e0e0', // 默认背景颜色
			},
			canvasWidth: {
				type: Number,
				default: 300, // 默认canvas宽度
			},
			canvasHeight: {
				type: Number,
				default: 20, // 默认canvas高度
			}
		},
		data() {
			return {
				canvasId: 'progressCanvas_' + Math.random().toString(36).substr(2, 9),
			};
		},
		mounted() {
			this.startCountdown();
		},
		methods: {
			startCountdown() {
				const ctx = uni.createCanvasContext(this.canvasId);
				const totalDuration = this.duration;
				const startTime = Date.now();

				const drawProgressBar = () => {
					const elapsed = Date.now() - startTime;
					const remainingTime = Math.max(totalDuration - elapsed, 0);
					const progress = 1 - remainingTime / totalDuration;

					ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
					ctx.setFillStyle(this.backgroundColor);
					ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);

					ctx.setFillStyle(this.progressBarColor);
					ctx.fillRect(0, 0, this.canvasWidth * progress, this.canvasHeight);

					ctx.draw();

					if (remainingTime > 0) {
						requestAnimationFrame(drawProgressBar);
					}
				};

				drawProgressBar();
			},
		},
	};
</script>

<style scoped>
	.container {
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>